#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>

using namespace std;

//int gval = 100;
//__thread修饰后，各线程会把变量放在自己的局部存储空间里，互不影响
//即每个线程私有一份(只在linux中有效，且只支持内置类型)
__thread int gval =100;

string ToHex(pthread_t tid)
{
    char id[128];
    snprintf(id, sizeof(id), "0x%lx", tid);
    return id;
}

void *threadRun(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        // ptread_self()线程获取自身的id

        cout << name << " is running ,tid: " << ToHex(pthread_self()) << " ,gval: " << gval << " ,&gval: " << &gval << endl;
        sleep(1);
        gval++;
        
    }
}

int main()
{
    pthread_t tid; // 线程属性集合的起始虚拟地址 --- 在pthread库中维护
    pthread_create(&tid, nullptr, threadRun, (void *)"thread-1");
    //cout << "new thread tid: " << ToHex(tid) << endl;
    while (true)
    {

        cout << "main thread is running ,gval: " << gval << " ,&gval: " << &gval << endl;
        //gval++;
        sleep(1);
    }
    pthread_join(tid, nullptr);
    return 0;
}